import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import { storeToRefs } from "pinia";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { constantRoutes } from "./routeMap";
import store, { usePermissionStore } from "../stores";
const allowList = ["/login"];
const router = createRouter({
    history: createWebHistory(), // createWebHistory为history模式  createWebHashHistory为hash模式
    routes: constantRoutes,
});
router.beforeEach((to, from, next) => {
    NProgress.configure({ showSpinner: false });
    NProgress.start();
    const permissionStoreData = usePermissionStore(store);
    const token = localStorage.getItem("ACCESS_TOKEN");
    if (token) {
        if (to.path === "/login") {
            next("/");
            NProgress.done();
        } else {
            const { permissionRoutes } = storeToRefs(permissionStoreData);
            if (permissionRoutes.value.length === 0) {
                const currentRole = localStorage.getItem(
                    "CURRENT_ROLE"
                ) as string;
                permissionStoreData
                    .getMenus(currentRole)
                    .then((d) => {
                        next({ ...to, replace: true });
                        NProgress.done();
                    })
                    .catch((e) => {
                        console.log("网络可能发生错误");
                    });
            } else {
                next();
                NProgress.done();
            }
        }
    } else {
        if (allowList.includes(to.path)) {
            next();
            NProgress.done();
        } else {
            next("/login");
            NProgress.done();
        }
    }
});
router.afterEach(() => {
    NProgress.done();
});
export default router;
// 重置路由
export function resetRouter() {
    router.getRoutes().forEach((route) => {
        const { path } = route;
        if (path && path !== "/login") {
            router.hasRoute(path) && router.removeRoute(path);
        }
    });
}
